/**
 * FormVendas.java
 * Copyright (C) 2009 Jose Mauro da Silva Sandy
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 * FormVendas.java
 *
 * Created on 04/07/2009, 10:34:28
 */

package frames;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import java.util.Date;
import java.util.Hashtable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import negocio.movimento.DivisaoLucro;
import negocio.movimento.Movimento;
import negocio.pessoas.Empreendimento;
import negocio.pessoas.InvestidorEmpreendimento;
import negocio.pessoas.Pessoa;
import persistencia.notas.PContasPagar;
import utils.*;

/**
 *
 * @author jmsandy
 */
public class FormVendas extends javax.swing.JDialog {

    //<editor-fold defaultstate="collapsed" desc="FIELDS">
    private ArrayList lstObj                                                     = null;
    private Empreendimento emp                                                 = null;
    private String errorMessage                                               = "";
    private int index                                                                   = -1;
    private ArrayList<InvestidorEmpreendimento> lstInv = null;
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Constructor">
    /** Creates new form FormVendas */
    public FormVendas() {
        initComponents();
        initalizeMyComponentes();
    }
    //</editor-fold>

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FormVendas().setVisible(true);
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanelPrinc = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableEmp = new javax.swing.JTable();
        lbEmp = new javax.swing.JLabel();
        textNome = new javax.swing.JTextField();
        lbDtVenda = new javax.swing.JLabel();
        textDtVenda = new javax.swing.JFormattedTextField();
        lbValorVenda = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        listInv = new javax.swing.JList();
        textValor = new javax.swing.JTextField();
        panelBotao = new javax.swing.JPanel();
        btnConfirmar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();

        setTitle("Venda e Divisão de Lucros");
        setFont(new java.awt.Font("Sawasdee", 0, 12));
        setName("formVendas"); // NOI18N
        setResizable(false);

        jPanelPrinc.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanelPrinc.setPreferredSize(new java.awt.Dimension(200, 456));

        tableEmp.setFont(new java.awt.Font("SansSerif", 0, 12));
        tableEmp.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Empreendimento", "Total Gastos"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Double.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tableEmp.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableEmpMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tableEmp);

        lbEmp.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbEmp.setText("*Empreendimento");

        textNome.setBackground(java.awt.Color.white);
        textNome.setEditable(false);

        lbDtVenda.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbDtVenda.setText("*Data da Venda");

        textDtVenda.setBackground(java.awt.Color.white);
        textDtVenda.setEditable(false);
        try {
            textDtVenda.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        textDtVenda.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        textDtVenda.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);
        textDtVenda.setFont(new java.awt.Font("SansSerif", 0, 12));

        lbValorVenda.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbValorVenda.setText("*Valor da Venda");

        listInv.setBackground(java.awt.Color.white);
        listInv.setFont(new java.awt.Font("SansSerif", 0, 10));
        listInv.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        listInv.setEnabled(false);
        listInv.setRequestFocusEnabled(false);
        jScrollPane2.setViewportView(listInv);

        textValor.setBackground(java.awt.Color.white);
        textValor.setEditable(false);
        textValor.setFont(new java.awt.Font("SansSerif", 0, 12));
        textValor.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        textValor.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                textValorFocusLost(evt);
            }
        });

        javax.swing.GroupLayout jPanelPrincLayout = new javax.swing.GroupLayout(jPanelPrinc);
        jPanelPrinc.setLayout(jPanelPrincLayout);
        jPanelPrincLayout.setHorizontalGroup(
            jPanelPrincLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelPrincLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelPrincLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelPrincLayout.createSequentialGroup()
                        .addGroup(jPanelPrincLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lbEmp)
                            .addComponent(lbDtVenda))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanelPrincLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanelPrincLayout.createSequentialGroup()
                                .addComponent(textDtVenda, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(104, 104, 104)
                                .addComponent(lbValorVenda)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(textValor, 0, 0, Short.MAX_VALUE))
                            .addComponent(textNome, javax.swing.GroupLayout.PREFERRED_SIZE, 368, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 479, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanelPrincLayout.setVerticalGroup(
            jPanelPrincLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelPrincLayout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addGroup(jPanelPrincLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 292, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanelPrincLayout.createSequentialGroup()
                        .addGroup(jPanelPrincLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lbEmp, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(textNome, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanelPrincLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lbDtVenda)
                            .addComponent(textDtVenda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lbValorVenda)
                            .addComponent(textValor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, 0, 0, Short.MAX_VALUE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanelPrincLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {textDtVenda, textNome, textValor});

        panelBotao.setBorder(javax.swing.BorderFactory.createEtchedBorder(null, java.awt.Color.gray));
        panelBotao.setFont(new java.awt.Font("DejaVu Sans", 0, 12));

        btnConfirmar.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnConfirmar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ok.png"))); // NOI18N
        btnConfirmar.setText("Confirmar");
        btnConfirmar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnConfirmarMouseClicked(evt);
            }
        });

        btnCancelar.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.setMaximumSize(new java.awt.Dimension(92, 34));
        btnCancelar.setMinimumSize(new java.awt.Dimension(92, 34));
        btnCancelar.setPreferredSize(new java.awt.Dimension(92, 34));
        btnCancelar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnCancelarMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout panelBotaoLayout = new javax.swing.GroupLayout(panelBotao);
        panelBotao.setLayout(panelBotaoLayout);
        panelBotaoLayout.setHorizontalGroup(
            panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelBotaoLayout.createSequentialGroup()
                .addGap(226, 226, 226)
                .addComponent(btnConfirmar, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(243, Short.MAX_VALUE))
        );
        panelBotaoLayout.setVerticalGroup(
            panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelBotaoLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE, false)
                    .addComponent(btnConfirmar)
                    .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(panelBotao, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanelPrinc, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 725, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(jPanelPrinc, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelBotao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(17, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-753)/2, (screenSize.height-435)/2, 753, 435);
    }// </editor-fold>//GEN-END:initComponents

    //<editor-fold defaultstate="collapsed" desc="Events">
    private void btnConfirmarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnConfirmarMouseClicked
        if(btnConfirmar.isEnabled() && emp != null){

            if(Double.parseDouble(textValor.getText()) <=
                                         (Double)tableEmp.getValueAt(index, 1)){
                showMessageWarning(ErrorMessage.MSG_DIV_VALOR);
            }

            // Realiza a confirmacao do movimento
            if(JOptionPane.showConfirmDialog(this, "Confirma a Venda e Divisão de"
                    +" Lucros do Empreendimento: \n"
                    + textNome.getText() + "?", "Confirmation",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE)
                    == JOptionPane.OK_OPTION){
                try{

                    if(validateFields()){
                        boolean ret = 
                         (new Movimento()).gerarMovimento(emp, createMovement(),
                         createListDivisao((Double)tableEmp.getValueAt(index, 1),
                                      Double.parseDouble(textValor.getText())));

                        if(ret){
                            showMessageInformation(ErrorMessage.MSG_DIV_INS);
                            DefaultTableModel dtm =
                                         (DefaultTableModel)tableEmp.getModel();
                            tableEmp.updateUI();
                            dtm.removeRow(index);
                            enableFields(false, "");
                            listInv.removeAll();
                            listInv.updateUI();
                            lstObj.remove(emp);
                            emp = null;
                            lstInv.clear();
                        }
                        else{
                            showMessageError(ErrorMessage.MSG_GERAL_BANCO + "\n"
                                           + ErrorMessage.MSG_GERAL_LOG);
                        }
                    }
                    else{
                        showMessageError(!errorMessage.equals("") ?
                           errorMessage : ErrorMessage.MSG_GERAL_OBRIG);
                    }
                } catch(Exception ex){
                    showMessageError(ErrorMessage.MSG_GERAL_BANCO + "\n"
                                           + ErrorMessage.MSG_GERAL_LOG);
                }
            }
        }
}//GEN-LAST:event_btnConfirmarMouseClicked

    private void btnCancelarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCancelarMouseClicked
        dispose();
}//GEN-LAST:event_btnCancelarMouseClicked

    private void tableEmpMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableEmpMouseClicked
        // Verifica se foi selecionado algum registro
        index = tableEmp.getSelectedRow();
        if(index > -1){
            emp = (Empreendimento)lstObj.get(index);

            showInvestidores();
            enableFields(true, (String)tableEmp.getValueAt(index, 0));
        }
        else{
            enableFields(false, "");
        }
    }//GEN-LAST:event_tableEmpMouseClicked

    private void textValorFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_textValorFocusLost
        try{
            if(textValor.isEnabled() &&  textValor.getText().trim().length() > 0){
                DecimalFormat format = new DecimalFormat("0.00");

                textValor.setText(format.format(
                Double.parseDouble(textValor.getText())).replace(',', '.'));
            }
        }
        catch(Exception ex){
            showMessageWarning(ErrorMessage.MSG_GERAL_FORMAT);
        }
    }//GEN-LAST:event_textValorFocusLost
    //</editor-fold>

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnConfirmar;
    private javax.swing.JPanel jPanelPrinc;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lbDtVenda;
    private javax.swing.JLabel lbEmp;
    private javax.swing.JLabel lbValorVenda;
    private javax.swing.JList listInv;
    private javax.swing.JPanel panelBotao;
    private javax.swing.JTable tableEmp;
    private javax.swing.JFormattedTextField textDtVenda;
    private javax.swing.JTextField textNome;
    private javax.swing.JTextField textValor;
    // End of variables declaration//GEN-END:variables

    //<editor-fold defaultstate="collapsed" desc="Methods">
    // Messagem de erro
    private void showMessageError(String msg){
        JOptionPane.showMessageDialog(this, msg, "Venda e Divisão de Lucros",
                                                    JOptionPane.ERROR_MESSAGE);
    }

    // Messagem de alerta
    private void showMessageInformation(String msg){
        JOptionPane.showMessageDialog(this, msg, "Venda e Divisão de Lucros",
                                               JOptionPane.INFORMATION_MESSAGE);
    }

    // Messagem de alerta
    private void showMessageWarning(String msg){
        JOptionPane.showMessageDialog(this, msg, "Venda e Divisão de Lucros",
                                               JOptionPane.WARNING_MESSAGE);
    }

    // Inicializa as colunas padroes da tabela
    private void initializeTable(){
        tableEmp.getColumnModel().getColumn(0).setPreferredWidth(390);
        tableEmp.getColumnModel().getColumn(0).setResizable(false);
        tableEmp.getColumnModel().getColumn(1).setPreferredWidth(86);
        tableEmp.getColumnModel().getColumn(1).setResizable(false);
        tableEmp.getColumnModel().getColumn(1).setCellRenderer(
                                                    Auxiliar.getAlign(Auxiliar.RIGHT));

        tableEmp.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        tableEmp.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    // Inicializa os componentes
    private void initalizeMyComponentes(){
        initializeTable();
        showRecords();
    }

    // Recupera e apresenta a lista de objeto
    private void showRecords(){
        DefaultTableModel dtm = (DefaultTableModel)tableEmp.getModel();
        tableEmp.updateUI();

        // Recupera a lista de Empreendimentos em finalizados
        lstObj = new ArrayList();
        lstObj = (new Empreendimento()).
                             recLstEmpSituacao(StatusEmpreendimento.FINALIZADO);

        // Insere os registros na tabela
        for(Empreendimento e : (ArrayList<Empreendimento>)lstObj){

            Object[] row = new Object[]{
                (new Pessoa().refresh(e.getPessoa()).getNome()),
                e.sumGastos(e.getCod_objeto())};
            dtm.addRow(row);
        }
    }

    // Apresenta a lista de investidores
    private void showInvestidores(){
        // Limpa a lista de investidores
        DefaultListModel dlm = new DefaultListModel();
        listInv.removeAll();
        listInv.updateUI();

        // Recupera a lista de investidores para o empreendimento
        lstInv =
              (new InvestidorEmpreendimento()).recLstDivLucro(emp.getCod_objeto());

        for(InvestidorEmpreendimento inv : lstInv){
            dlm.addElement(new Pessoa().
                                recPessoaInvestidor(inv.getInvestidor()).getNome());
        }

        listInv.setModel(dlm);
    }

    private void enableFields(boolean flag, String nome){
        if(flag){
            textNome.setText(nome);
            textValor.setText("0.00");
        }
        else{
            textNome.setText("");
            textValor.setText("");
            textDtVenda.setText("");
        }

        btnConfirmar.setEnabled(flag);
        textDtVenda.setEditable(flag);
        textValor.setEditable(flag);
    }

    // Recupera todos os registros selecionados
    private ArrayList<DivisaoLucro> createListDivisao(Double valorGasto,
                                                            Double valorVenda){
        ArrayList<DivisaoLucro> lstDiv = new ArrayList<DivisaoLucro>();
        Hashtable<String, Double> table = new Hashtable<String, Double>();

        try{
            table = (new PContasPagar()).recLstContasPorEmpInv(emp.getCod_objeto());
            for(InvestidorEmpreendimento inv : lstInv){
                DivisaoLucro dl = new DivisaoLucro();
                Double valPago = table.get(inv.getInvestidor());

                dl.setCod_objeto(GenerateID.gerarID());
                dl.setEmpreendimento(emp.getCod_objeto());
                dl.setInvestidor(inv.getInvestidor());
                dl.setValorRecebido(getLucro(valorVenda, valPago, valorGasto));

                lstDiv.add(dl);
            }
        }
        catch(IOException ex){
            lstDiv = null;
        }
        return lstDiv;
    }

    // Cria movimento
    private Movimento createMovement(){
        Movimento mov = new Movimento();

        mov.setCod_objeto(GenerateID.gerarID());
        mov.setEmpreendimento(emp.getCod_objeto());
        mov.setTipoMovimento(TipoMovimento.VENDA);

        return mov;
    }

    // Apura o lucro de uma dada pessoa
    private Double getLucro(Double valorVenda, Double valorPago, Double valorTotPg){
        Double lucro = 0.00;
        lucro = (valorVenda / valorTotPg) * valorPago;
        return lucro;
    }

    // Mapeia os filtros e valida os campos
    private boolean validateFields(){
        boolean valid = false;

        try{
            errorMessage = "";

            // Formato padrao das dadas do sistema
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            sdf.setLenient(false);
            emp.setValorVenda(textValor.getText().isEmpty() ?
                     0 : Double.parseDouble(textValor.getText()));
            emp.setDtVenda(
                    (!textDtVenda.getText().equals("  /  /    ")) ?
                     new Date(sdf.parse(textDtVenda.getText()).getTime()) : null);

            if(emp.getValorVenda() > 0 && emp.getDtVenda() != null){
                Date date = new Date();
                valid = date.getTime() >= emp.getDtVenda().getTime() ?
                                                                   true : false;

                if(valid && emp.getDataInicio() != null){
                    valid = emp.getDataInicio().getTime() <=
                            emp.getDtVenda().getTime() ? true : false;
                }

                if(!valid) this.errorMessage = ErrorMessage.MSG_GERAL_DATA;
                else emp.setStatus(StatusEmpreendimento.VENDIDO);
            }
        }
        catch(Exception ex){
            ex.printStackTrace();
            valid = false;
        }
        return valid;
    }
    //</editor-fold>
}